package ace.tool.generate.code.impl.resolver.scheme.resolver.core;

import ace.tool.generate.code.impl.resolver.scheme.model.bo.core.EntityClassInfo;
import ace.tool.generate.code.impl.resolver.scheme.model.bo.core.resources.GraphqlInputFileInfo;
import ace.tool.generate.code.impl.resolver.scheme.model.bo.core.resources.model.dto.DaoEntityModelField;
import ace.tool.generate.code.impl.resolver.scheme.model.bo.core.resources.model.dto.GraphqlTemplateModel;
import ace.tool.generate.code.impl.resolver.scheme.model.bo.core.resources.model.dto.GraphqlTemplateModelField;
import ace.tool.generate.code.impl.resolver.scheme.model.dto.ProjectInfo;
import ace.tool.generate.code.impl.service.model.input.GenerateInput;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.apache.commons.text.StringSubstitutor;

/**
 * @author caspar
 * @date 2023/11/17 10:34
 */
@RequiredArgsConstructor
public class GraphqlInputFileInfoResolver {
  private final GenerateInput input;
  private final EntityClassInfo entityClassInfo;
  private final ProjectInfo coreProjectInfo;

  public GraphqlInputFileInfo resolve() {

    return GraphqlInputFileInfo.builder()
        .entityModelId(entityClassInfo.getEntityModelId())
        .fileName(entityClassInfo.getModel().getClassName())
        .fileFullName(this.getFileFullName())
        .model(this.getModel())
        .build();
  }

  private GraphqlTemplateModel getModel() {
    return GraphqlTemplateModel.builder()
        .name(entityClassInfo.getModel().getClassName() + "Input")
        .remark(entityClassInfo.getModel().getRemark())
        .fields(this.getFields())
        .build();
  }

  private List<GraphqlTemplateModelField> getFields() {
    return this.entityClassInfo.getModel().getFields().stream()
        .map(this::getField)
        .collect(Collectors.toList());
  }

  private GraphqlTemplateModelField getField(DaoEntityModelField daoEntityModelField) {
    String type =
        GraphqlTypeResolver.builder()
            .type(daoEntityModelField.getTypeClass())
            .idFlag(daoEntityModelField.getIdFlag())
            .build()
            .resolve();
    return GraphqlTemplateModelField.builder()
        .idFlag(daoEntityModelField.getIdFlag())
        .name(daoEntityModelField.getName())
        .remark(daoEntityModelField.getRemark())
        .type(type)
        .build();
  }

  private String getFileFullName() {
    Map<String, String> data = new HashMap<>();
    data.put("fileName", entityClassInfo.getModel().getClassName() + "Input");
    data.put("resourcesRootDir", coreProjectInfo.getResourcesRootDir());
    data.put("rootDirPrefix", input.getGraphqlSchemaInputRootDirPrefix());
    return StringSubstitutor.replace(
        "${resourcesRootDir}/${rootDirPrefix}/${fileName}.graphqls", data);
  }
}
